<?php

namespace globalunit\utils;
use QYS\Core\Config;


function gmt_iso8601($time) {
    $dtStr = date("c", $time);
    $mydatetime = new \DateTime($dtStr);
    $expiration = $mydatetime->format(\DateTime::ISO8601);
    $pos = strpos($expiration, '+');
    $expiration = substr($expiration, 0, $pos);
    return $expiration."Z";
}

class OssToken{

    private $bucket = null;
    private $endpoint = null;
    private $accessKey = null;
    private $secretKey = null;
    private $host = null;
    private $callbackUrl = null;
    private $key = null;
    private $dir = null;


    public function __construct()
    {
        $this->bucket    = Config::get('bucket');
        $this->endpoint  = Config::get('Endpoint');
        $this->accessKey = Config::get('AccessKeyId');
        $this->secretKey = Config::get('AccessKeySecret');
        $this->host = 'http://'.$this->bucket.'.'.$this->endpoint;
        var_dump($this->host);
    }

    public function getOssConfig($config){
        $this->dir = date('Y-m-d').'/';
        $this->callbackUrl = $config['callbackUrl'];
        $this->key = $this->dir.$config['filename'];
        if(empty($this->callbackUrl) || empty($this->key)){
            return false;
        }
        $callback_param = [
//                            'callbackUrl'=>$this->callbackUrl,
                            'callbackBody'=>'filename=${object}&size=${size}&mimeType=${mimeType}&height=${imageInfo.height}&width=${imageInfo.width}',
                            'callbackBodyType'=>"application/x-www-form-urlencoded"
                          ];
        var_dump($callback_param);
        $callback_string = json_encode($callback_param);
        $base64_callback_body = base64_encode($callback_string);
        $now = time();
        $expire = isset($config['expire']) ? $config['expire'] : 10;  //设置该policy超时时间是10s. 即这个policy过了这个有效时间，将不能访问。
        $end = $now + $expire;
        $expiration = gmt_iso8601($end);
        //最大文件大小.用户可以自己设置
        $condition = [0 => 'content-length-range', 1 => 0, 2 => 1024 * 1024 * 50];
        $conditions[] = $condition;
        // 表示用户上传的数据，必须是以$dir开始，不然上传会失败，这一步不是必须项，只是为了安全起见，防止用户通过policy上传到别人的目录。
        $start = [0 => 'starts-with', 1 => $this->key, 2 => $this->dir];
        $conditions[] = $start;
        $arr = ['expiration' => $expiration, 'conditions' => $conditions];
        $policy = json_encode($arr);
        $base64_policy = base64_encode($policy);
        $string_to_sign = $base64_policy;
        $signature = base64_encode(hash_hmac('sha1', $string_to_sign, $this->secretKey, true));
        $response = [];
        $response['accessid'] = $this->accessKey;
        $response['host'] =  $this->host;
        $response['policy'] = $base64_policy;
        $response['signature'] = $signature;
        $response['expire'] = $end;
        $response['callback'] = $base64_callback_body;
        $response['dir'] =  $this->dir;  // 这个参数是设置用户上传文件时指定的前缀。
        return $response;
    }


}


